574B - Bear and Three Musketeers - CodeForces Solution


brute force dfs and similar graphs hashing *1500

Please click on ads to support us..

Python Code:

n, m=[int(k) for k in input().split()]
w=[]
for j in range(m):
    w.append([int(k) for k in input().split()])
q={}
rho={}
for j in range(m):
    if w[j][0] in q:
        q[w[j][0]].append(w[j][1])
    else:
        q[w[j][0]]=[w[j][1]]
    if w[j][1] in q:
        q[w[j][1]].append(w[j][0])
    else:
        q[w[j][1]]=[w[j][0]]
for j in q.keys():
    rho[j]=set(q[j])
c={}
for j in q.keys():
    c[j]=len(q[j])
mn=10**100
for j in q.keys():
    for k in range(c[j]-1):
        for l in range(k, c[j]):
            if q[j][k] in rho[q[j][l]]:
                mn=min(mn, c[j]+c[q[j][k]]+c[q[j][l]])

if mn>=10**100:
    print(-1)
else:
    print(mn-2*3)

C++ Code:

#include <bits/stdc++.h>

using namespace std;

#define       TASK  "TEST"
#define       lint  long long int
#define      sz(v)  (int(v.size()))
#define    ynif(c)  cout << ((c) ? "YES\n" : "NO\n")
#define     all(v)  v.begin(), v.end()
#define    rall(v)  v.rbegin(), v.rend()
#define    exetime  cerr << "Time elapsed: " << (1.0 * clock() / CLOCKS_PER_SEC) << "s"

bool know[4043][4043];
int n, m, deg[4043], u, v, Z;
vector <int> a[4043];

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    if (fopen(TASK".INP", "r")) {
        freopen(TASK".INP", "r", stdin);
        freopen(TASK".OUT", "w", stdout);
    }
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        cin >> u >> v;
        deg[u]++;
        deg[v]++;
        know[u][v] = know[v][u] = 1;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    Z = -1;
    for (int i = 1; i <= n; i++)
        for (int j : a[i])
            for (int k : a[i])
                if (j != k && know[j][k]) {
                    int rec = deg[i] + deg[j] + deg[k] - 6;
                    if (Z == -1) Z = rec;
                    else Z = min(Z, rec);
                }
    cout << Z;
    return exetime, 0;
}


Comments

Submit
0 Comments
More Questions

1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas